package com.res.common.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.res.simulator.handler.CatalogManagementHandler;
import com.res.simulator.handler.CommonFileHandler;
import com.res.simulator.model.CatalogManagementControlModel;
import com.res.simulator.view.CatalogManagementView;
import com.res.system.properties.PropertySelector;

@Controller
@SessionAttributes
public class CatalogManagementPageController extends BaseController {

	// get log4j handler
	private static final Logger logger = Logger.getLogger(CatalogManagementPageController.class);

	@RequestMapping("/cataloguemanagement")
	public String home(@ModelAttribute("CatalogManagementCatagory") CatalogManagementControlModel catalogManagementControlModel) {

		final Map<String, String> catalogManagementAPICategoryMap = PropertySelector.getInstance().select("sam6catalogapimapping");

		getSession().setAttribute("catalogManagementCategoryMap", catalogManagementAPICategoryMap.keySet());
		
		if (null == getSession().getAttribute("catalogAPIMap")) {

			final Map<String, String> catagoryApiMap = PropertySelector.getInstance().select("RetailCatalogAPI");
			getSession().setAttribute("catalogAPIMap", catagoryApiMap.keySet());
			getSession().setAttribute("selectedApiCatagory", "RetailCatalogAPI");

		}

		return "catalogmanagementlayout";
	}

	@RequestMapping(value = "/process_cm_api", method = RequestMethod.GET, params = "apiCategory")
	protected String invokeCatalogCatagory(@ModelAttribute("CatalogManagementCatagory") final CatalogManagementControlModel catalogManagementControlModel,
			final BindingResult result) throws Exception {

		final String apiCategory = catalogManagementControlModel.getApiCategory();
		final Map<String, String> catagoryApiMap = PropertySelector.getInstance().select(apiCategory);

		if (null != apiCategory) {
			getSession().setAttribute("apiCatagory", apiCategory);
			getSession().setAttribute("selectedApiCatagory", apiCategory);
		}

		getSession().setAttribute("catalogAPIMap", catagoryApiMap.keySet());
		getSession().setAttribute("selectedAPIParam", "");

		return "redirect:cataloguemanagement.htm";
	}

	@RequestMapping(value = "/process_cm_api", method = RequestMethod.GET, params = {"apiCategory","selectedAPI"})
	protected String changeAPI(
			@ModelAttribute("CatalogManagementCatagory") final CatalogManagementControlModel catalogManagementControlModel,
			final BindingResult result) throws Exception {

		final String selectedAPI = catalogManagementControlModel.getSelectedAPI();
		final String apiCatagory = catalogManagementControlModel.getApiCategory();

		final String inputParameters = PropertySelector.getInstance().select(apiCatagory, selectedAPI);
		getSession().setAttribute("selectedAPIName", selectedAPI);

		if (null != inputParameters) {
			getSession().setAttribute("selectedAPIParam", inputParameters);
		}

		return "redirect:cataloguemanagement.htm";
	}

	@RequestMapping(value = "/process_cm_api", method = RequestMethod.GET, params = {"apiCategory","inputParameter","InvokeAPI"})
	protected String invokeAPI(
			@ModelAttribute("CatalogManagementCatagory") final CatalogManagementControlModel catalogManagementControlModel,
			final BindingResult result) throws Exception {

		if (null != catalogManagementControlModel.getApiCategory() && null != catalogManagementControlModel.getInputParameter()
				&& null != catalogManagementControlModel.getSelectedAPI()) {

			final CatalogManagementHandler handler = new CatalogManagementHandler();
			final CatalogManagementView view = handler.process(catalogManagementControlModel);

			List<CatalogManagementView> catalogManangementCollection = (List<CatalogManagementView>) getSession().getAttribute(
					"CatalogManagementViewCollection");

			if (null == catalogManangementCollection) {
				catalogManangementCollection = new LinkedList<CatalogManagementView>();
			}

			catalogManangementCollection.add(view);
			getSession().setAttribute("CatalogManagementViewCollection", catalogManangementCollection);
		}

		return "redirect:cataloguemanagement.htm";
	}

	@RequestMapping(value = "/invokeCatalogManagement", method = RequestMethod.GET, params = { "clearHistory", "apiCategory", "inputParameter" })
	protected String clear(@ModelAttribute("CatalogManagementCatagory") final CatalogManagementControlModel catalogManagementControlModel,
			final BindingResult result) throws Exception {

		final List<CatalogManagementView> catalogManangementCollection = (List<CatalogManagementView>) getSession().getAttribute(
				"CatalogManagementViewCollection");

		if (null != catalogManangementCollection) {
			catalogManangementCollection.clear();
		}

		return "redirect:CatalogManagementPage.htm";
	}

	@RequestMapping(value = "/downloadCMResponseXML", method = RequestMethod.GET)
	public String downloadFile(final HttpServletRequest request, HttpServletResponse response) throws IOException {

		final List<CatalogManagementView> catalogManangementCollection = (List<CatalogManagementView>) getSession().getAttribute(
				"CatalogManagementViewCollection");
		
		final String id = (String) request.getParameter("viewId");
		CatalogManagementView selectedView = null;

		for (final CatalogManagementView catalogManagementView : catalogManangementCollection) {

			if (catalogManagementView.getId().equals(id)) {
				selectedView = catalogManagementView;
				break;
			}

		}

		response.setContentType("application/xml");
		response.addHeader("Content-disposition", "atachment; filename=CM_" + selectedView.getId());

		final OutputStream buffoutput = new BufferedOutputStream(response.getOutputStream());
		final OutputStreamWriter outputwriter = new OutputStreamWriter(buffoutput);

		final CommonFileHandler fileHandler = new CommonFileHandler();
		final StringBuilder stringBuilder = fileHandler.read(selectedView.getLocation());

		outputwriter.write(stringBuilder.toString());

		outputwriter.flush();
		outputwriter.close();

		return "redirect:CatalogManagementPage.htm";

	}

}
